<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title th:text="${pageTitle ?: '同步平台 - 数据库同步任务'}">同步平台 - 数据库同步任务</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.3/font/bootstrap-icons.css">
    <link rel="stylesheet" th:href="@{/css/style.css}">
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar Navigation -->
            <nav id="sidebar" class="col-md-3 col-lg-2 d-md-block bg-dark sidebar collapse">
                <div class="position-sticky pt-3">
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link" th:href="@{/}">
                                <i class="bi bi-house"></i> 首页
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" th:href="@{/dashboard}">
                                <i class="bi bi-speedometer2"></i> 仪表盘
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" th:href="@{/server}">
                                <i class="bi bi-server"></i> 服务器管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" th:href="@{/database}">
                                <i class="bi bi-database"></i> 数据库管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link active" th:href="@{/sync/database}">
                                <i class="bi bi-arrow-left-right"></i> 数据库同步
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" th:href="@{/sync/file}">
                                <i class="bi bi-files"></i> 文件同步
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" th:href="@{/restore}">
                                <i class="bi bi-arrow-counterclockwise"></i> 数据库恢复
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" th:href="@{/task/log}">
                                <i class="bi bi-list-check"></i> 同步日志
                            </a>
                        </li>
                    </ul>
                </div>
            </nav>
            
            <!-- Main Content -->
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">添加数据库同步任务</h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <a th:href="@{/sync/database}" class="btn btn-sm btn-outline-secondary">
                            <i class="bi bi-arrow-left"></i> 返回列表
                        </a>
                    </div>
                </div>
                
                <!-- Database Sync Task Form -->
                <div class="card">
                    <div class="card-body">
                        <div class="alert alert-info">
                            <i class="bi bi-info-circle"></i> 数据库同步功能正在开发中。您需要先配置源数据库和目标数据库，然后才能创建同步任务。
                        </div>
                        
                        <form id="syncTaskForm" class="needs-validation" novalidate>
                            <!-- Hidden task ID field for editing -->
                            <input type="hidden" id="taskId" name="taskId" th:value="${task != null ? task.id : ''}">
                            
                            <!-- Basic Info -->
                            <div class="card mb-4">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">基本信息</h5>
                                </div>
                                <div class="card-body">
                                    <div class="mb-3">
                                        <label for="taskName" class="form-label">任务名称</label>
                                        <input type="text" class="form-control" id="taskName" name="taskName" th:value="${task != null ? task.name : ''}" required>
                                        <div class="invalid-feedback">请输入任务名称</div>
                                    </div>
                                    <div class="mb-3">
                                        <label for="description" class="form-label">描述</label>
                                        <textarea class="form-control" id="description" name="description" rows="3" th:text="${task != null ? task.lastExecutionMessage : ''}"></textarea>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Source and Target Database -->
                            <div class="card mb-4">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">数据库配置</h5>
                                </div>
                                <div class="card-body">
                                    <div class="row">
                                        <!-- Source Database -->
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label for="sourceDatabase" class="form-label">源数据库</label>
                                                <select class="form-select" id="sourceDatabase" name="sourceDatabase" required>
                                                    <option value="">选择源数据库</option>
                                                    <option th:each="db : ${databases}" th:value="${db.id}" 
                                                            th:text="${db.name + ' (' + db.dbType + ')'}"
                                                            th:selected="${task != null && task.sourceId == db.id}"></option>
                                                </select>
                                                <div class="invalid-feedback">请选择源数据库</div>
                                            </div>
                                            <div class="mb-3">
                                                <label for="sourceTables" class="form-label">源表</label>
                                                <select class="form-select" id="sourceTables" name="sourceTables" multiple th:disabled="${task == null}">
                                                    <option value="" th:if="${task == null}">请先选择源数据库</option>
                                                </select>
                                                <div class="form-text">选择要同步的表（不选择则同步全部表）</div>
                                            </div>
                                        </div>
                                        
                                        <!-- Target Database -->
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label for="targetDatabase" class="form-label">目标数据库</label>
                                                <select class="form-select" id="targetDatabase" name="targetDatabase" required>
                                                    <option value="">选择目标数据库</option>
                                                    <option th:each="db : ${databases}" th:value="${db.id}" 
                                                            th:text="${db.name + ' (' + db.dbType + ')'}"
                                                            th:selected="${task != null && task.targetId == db.id}"></option>
                                                </select>
                                                <div class="invalid-feedback">请选择目标数据库</div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Sync Options -->
                            <div class="card mb-3">
                                <div class="card-header">
                                    <h5 class="mb-0">同步选项</h5>
                                </div>
                                <div class="card-body">
                                    <div class="form-check mb-3">
                                        <input type="checkbox" class="form-check-input" id="createTableIfNotExists" name="createTableIfNotExists" checked>
                                        <label class="form-check-label" for="createTableIfNotExists">
                                            如果目标表不存在则创建
                                        </label>
                                        <div class="form-text">
                                            勾选此选项，如果目标数据库中不存在对应的表，将会自动创建
                                        </div>
                                    </div>
                                    
                                    <div class="form-check mb-3">
                                        <input type="checkbox" class="form-check-input" id="truncateBeforeSync" name="truncateBeforeSync">
                                        <label class="form-check-label" for="truncateBeforeSync">
                                            同步前清空目标表
                                        </label>
                                        <div class="form-text">
                                            勾选此选项，在同步前会先清空目标表中的所有数据
                                        </div>
                                    </div>
                                    
                                    <div class="form-check mb-3">
                                        <input type="checkbox" class="form-check-input" id="incrementalSync" name="incrementalSync">
                                        <label class="form-check-label" for="incrementalSync">
                                            增量同步
                                        </label>
                                        <div class="form-text">
                                            勾选此选项，仅同步上次成功同步后新增或修改的数据
                                        </div>
                                    </div>
                                    
                                    <div class="mb-3" id="incrementalColumnContainer" style="display: none;">
                                        <label for="incrementalColumn" class="form-label">增量同步字段</label>
                                        <input type="text" class="form-control" id="incrementalColumn" name="incrementalColumn" 
                                               placeholder="如：update_time, modified_at">
                                        <div class="form-text">
                                            请指定用于增量同步的时间戳字段，该字段应该在数据更新时自动更新为当前时间
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Enable Schedule -->
                            <div class="card mb-4">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">启用定时任务</h5>
                                </div>
                                <div class="card-body">
                                    <div class="form-check mb-3">
                                        <input class="form-check-input" type="checkbox" id="enableSchedule" name="enableSchedule" 
                                               th:checked="${task != null && task.cronExpression != null && !task.cronExpression.isEmpty()}">
                                        <label class="form-check-label" for="enableSchedule">
                                            启用定时任务
                                        </label>
                                    </div>
                                    <div class="mb-3">
                                        <label for="cronExpression" class="form-label">Cron 表达式</label>
                                        <input type="text" class="form-control" id="cronExpression" name="cronExpression" 
                                               placeholder="0 0 * * * ?" th:value="${task != null ? task.cronExpression : ''}" 
                                               th:disabled="${task == null || task.cronExpression == null || task.cronExpression.isEmpty()}">
                                        <div class="form-text">定时任务执行时间（Cron 表达式）</div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Submit Button -->
                            <div class="d-grid">
                                <button type="submit" class="btn btn-primary">保存同步任务</button>
                            </div>
                        </form>
                    </div>
                </div>
            </main>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.3/dist/jquery.min.js"></script>
    <script th:src="@{/js/script.js}"></script>
    
    <script th:inline="javascript">
        $(document).ready(function() {
            // Context path for API calls
            const contextPath = /*[[@{/}]]*/ '';
            
            // For edit page, load existing configuration
            const taskData = /*[[${task}]]*/ null;
            
            if (taskData) {
                // Populate the form with task data
                $('#taskId').val(taskData.id);
                $('#taskName').val(taskData.name);
                $('#description').val(taskData.description);
                $('#sourceDatabase').val(taskData.sourceId);
                $('#targetDatabase').val(taskData.targetId);
                
                // Load config JSON
                if (taskData.config) {
                    try {
                        const config = JSON.parse(taskData.config);
                        
                        // Set sync options
                        if (config.createTableIfNotExists !== undefined) {
                            $('#createTableIfNotExists').prop('checked', config.createTableIfNotExists);
                        }
                        
                        if (config.truncateBeforeSync !== undefined) {
                            $('#truncateBeforeSync').prop('checked', config.truncateBeforeSync);
                        }
                        
                        // Handle incremental sync options
                        if (config.incrementalSync !== undefined) {
                            $('#incrementalSync').prop('checked', config.incrementalSync);
                            
                            if (config.incrementalSync) {
                                $('#incrementalColumnContainer').show();
                                $('#incrementalColumn').val(config.incrementalColumn || '');
                            }
                        }
                        
                        // Load selected tables
                        if (config.tables) {
                            loadSourceTables();
                        }
                    } catch (e) {
                        console.error('Error parsing task config:', e);
                    }
                }
                
                // Set schedule options
                if (taskData.cronExpression) {
                    $('#enableSchedule').prop('checked', true);
                    $('#scheduleOptions').show();
                    $('#cronExpression').val(taskData.cronExpression);
                }
            }
            
            // Show/hide schedule options
            $('#enableSchedule').on('change', function() {
                if ($(this).is(':checked')) {
                    $('#scheduleOptions').slideDown();
                } else {
                    $('#scheduleOptions').slideUp();
                }
            });
            
            // Show/hide incremental column field
            $('#incrementalSync').on('change', function() {
                if ($(this).is(':checked')) {
                    $('#incrementalColumnContainer').slideDown();
                } else {
                    $('#incrementalColumnContainer').slideUp();
                }
            });
            
            // Handle "Select Tables" option change
            $('#selectTablesToggle').on('change', function() {
                if ($(this).val() === "1") {
                    $('#sourceTablesContainer').slideDown();
                    loadSourceTables();
                } else {
                    $('#sourceTablesContainer').slideUp();
                }
            });
            
            // Load source database tables when source database is selected
            $('#sourceDatabase').change(function() {
                const sourceId = $(this).val();
                if (sourceId) {
                    loadSourceTables(sourceId);
                } else {
                    $('#sourceTables').html('<option value="">请先选择源数据库</option>');
                    $('#sourceTables').prop('disabled', true);
                    // Remove any existing alerts
                    $('#tableLoadingAlert, #tableSuccessAlert, #tableWarningAlert, #tableErrorAlert').remove();
                }
            });
            
            // Function to load source tables with optional selected tables
            function loadSourceTables(sourceId, selectedTables) {
                const selectedDbName = $("#sourceDatabase option:selected").text();
                $('#sourceTables').prop('disabled', true);
                $('#sourceTables').html('<option value="">加载中...</option>');
                
                // Remove any existing alerts
                $('#tableLoadingAlert, #tableSuccessAlert, #tableWarningAlert, #tableErrorAlert').remove();
                
                // Show loading indicator
                const loadingMsg = $('<div class="alert alert-info mt-2" id="tableLoadingAlert">')
                    .html('<i class="bi bi-arrow-repeat"></i> 正在加载数据库 <strong>' + selectedDbName + '</strong> 的表...');
                $('#sourceDatabase').after(loadingMsg);
                
                $.ajax({
                    url: contextPath + 'database/' + sourceId + '/tables',
                    type: 'GET',
                    success: function(response) {
                        // Remove loading indicator
                        $('#tableLoadingAlert').remove();
                        
                        if (response.success && response.data && response.data.length > 0) {
                            $('#sourceTables').html('');
                            
                            $.each(response.data, function(i, table) {
                                const selected = selectedTables && 
                                                 selectedTables.indexOf(table) !== -1;
                                
                                $('#sourceTables').append(
                                    '<option value="' + table + '"' + 
                                    (selected ? ' selected' : '') + 
                                    '>' + table + '</option>'
                                );
                            });
                            
                            $('#sourceTables').prop('disabled', false);
                            
                            // Show success message
                            const successMsg = $('<div class="alert alert-success mt-2" id="tableSuccessAlert">')
                                .html('<i class="bi bi-check-circle"></i> 成功加载 <strong>' + response.data.length + 
                                    '</strong> 个表从数据库 <strong>' + selectedDbName + '</strong>');
                            $('#sourceDatabase').after(successMsg);
                            setTimeout(() => $('#tableSuccessAlert').fadeOut('slow', function() { $(this).remove(); }), 5000);
                        } else {
                            $('#sourceTables').html('<option value="">未找到表</option>');
                            
                            // Show warning message
                            const warningMsg = $('<div class="alert alert-warning mt-2" id="tableWarningAlert">')
                                .html('<i class="bi bi-exclamation-triangle"></i> 在数据库 <strong>' + 
                                    selectedDbName + '</strong> 中未找到表');
                            $('#sourceDatabase').after(warningMsg);
                        }
                    },
                    error: function(xhr, status, error) {
                        // Remove loading indicator
                        $('#tableLoadingAlert').remove();
                        
                        $('#sourceTables').html('<option value="">加载失败</option>');
                        
                        // Show error message
                        const errorMsg = $('<div class="alert alert-danger mt-2" id="tableErrorAlert">')
                            .html('<i class="bi bi-x-circle"></i> 加载表失败: ' + error);
                        $('#sourceDatabase').after(errorMsg);
                        console.error('Error loading tables:', xhr.responseText);
                    }
                });
            }
            
            // Form validation and submission
            $('#syncTaskForm').submit(function(event) {
                event.preventDefault();
                event.stopPropagation();
                
                const form = this;
                form.classList.add('was-validated');
                
                if (form.checkValidity()) {
                    // Create data object for submission
                    const formData = {
                        id: /*[[${task != null ? task.id : null}]]*/ null,
                        taskName: $('#taskName').val(),
                        description: $('#description').val(),
                        sourceDatabase: $('#sourceDatabase').val(),
                        targetDatabase: $('#targetDatabase').val(),
                        enableSchedule: $('#enableSchedule').is(':checked'),
                        cronExpression: $('#enableSchedule').is(':checked') ? $('#cronExpression').val() : null,
                        createTableIfNotExists: $('#createTableIfNotExists').is(':checked'),
                        truncateBeforeSync: $('#truncateBeforeSync').is(':checked'),
                        incrementalSync: $('#incrementalSync').is(':checked'),
                        incrementalColumn: $('#incrementalColumn').val()
                    };
                    
                    // Add selected source tables if any are selected
                    const selectedTables = $('#sourceTables').val();
                    if (selectedTables && selectedTables.length > 0) {
                        formData.sourceTables = selectedTables;
                    }
                    
                    // Show loading indicator
                    const loadingMsg = $('<div class="alert alert-info mt-2" id="saveLoadingAlert">')
                        .html('<i class="bi bi-arrow-repeat"></i> 正在保存同步任务...');
                    $(form).after(loadingMsg);
                    
                    // Submit form data
                    $.ajax({
                        url: contextPath + 'sync/database/save',
                        type: 'POST',
                        contentType: 'application/json',
                        data: JSON.stringify(formData),
                        success: function(response) {
                            // Remove loading indicator
                            $('#saveLoadingAlert').remove();
                            
                            if (response.success) {
                                // Show success message
                                const successMsg = $('<div class="alert alert-success mt-2" id="saveSuccessAlert">')
                                    .html('<i class="bi bi-check-circle"></i> 同步任务保存成功');
                                $(form).after(successMsg);
                                
                                // Redirect to list page after a short delay
                                setTimeout(() => {
                                    window.location.href = contextPath + 'sync/database';
                                }, 2000);
                            } else {
                                // Show error message
                                const errorMsg = $('<div class="alert alert-danger mt-2" id="saveErrorAlert">')
                                    .html('<i class="bi bi-x-circle"></i> 保存失败: ' + response.message);
                                $(form).after(errorMsg);
                            }
                        },
                        error: function(xhr, status, error) {
                            // Remove loading indicator
                            $('#saveLoadingAlert').remove();
                            
                            // Show error message
                            const errorMsg = $('<div class="alert alert-danger mt-2" id="saveErrorAlert">')
                                .html('<i class="bi bi-x-circle"></i> 保存失败: ' + error);
                            $(form).after(errorMsg);
                            console.error('Error saving task:', xhr.responseText);
                        }
                    });
                }
            });
        });
    </script>
</body>
</html> 